import random
import pymongo

class getRandomProxyUtil():
    
    def __init__(self):
        self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")
        if "proxy" not in self.myclient.list_database_names():
            raise Exception("不存在[proxy]数据库")
        self.mydb = self.myclient["proxy"]
        if "proxy_kuai" not in self.mydb.list_collection_names():
            raise Exception("不存在[proxy_kuai]集合")
        self.mycol = self.mydb["proxy_kuai"]
  
    def getRandomProxy(self):
        proxyList = self.mycol.find({'isDeleted': 0}).limit(40)
        item = random.sample(list(proxyList), 1)[0]
        if item['type'] == 'HTTP':
            return 'http://'+item['ip']+":"+item['port']
        if item['type'] == 'HTTPS':
            return 'https://'+item['ip']+":"+item['port']